/*
 * Copyright [2009] [Marcin Rzeźnicki]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mr.go.yaxc.actions;

import java.util.LinkedList;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.apache.commons.beanutils.MethodUtils;
import org.xml.sax.Attributes;

/**
 * This action calls instance method on parent object when processed
 * 
 * <h6>on xml element start:</h6> Sets <i>params</i> <h6>on xml element end:</h6>
 * Calls method <i>name</i> on <i>parentObject</i> with <i>params</i> as actual
 * arguments <h6>prerequisites:</h6> <i>parentObject</i> set <h6>attributes:</h6>
 * <table>
 * <tr>
 * <th>Attribute name</th>
 * <th>What is it for?</th>
 * <th>Required?</th>
 * </tr>
 * <tr>
 * <td><i>name</i></td>
 * <td>method name to call</td>
 * <td>yes</td>
 * </tr>
 * </table>
 *<p>
 * Example:<br>
 * 
 * <pre>
 * 	&lt;New class=&quot;mr.go.yaxc.tests.test1.Bean&quot; id=&quot;bean&quot;&gt;
 * 		&lt;Call name=&quot;setList&quot;&gt;
 * 			&lt;List&gt;
 * 				&lt;String&gt;a&lt;/String&gt;
 * 				&lt;String&gt;b&lt;/String&gt;
 * 				&lt;String&gt;c&lt;/String&gt;
 * 			&lt;/List&gt;
 * 		&lt;/Call&gt;
 * 	&lt;/New&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class CallMethod extends Action {

    private String methodName;

    @Override
    public void carryOut(String name, Attributes attributes,
                         ScopeHandler handler)
            throws Exception {
        methodName = attributes.getValue(getAttribute("name"));
        if (methodName == null) {
            throw new ConfigurationError("Missing attribute: " + getAttribute(
                    "name"));
        }
        params = new LinkedList<Object>();

    }

    @Override
    public void processed(String body, ScopeHandler handler)
            throws Exception {
        final Object o = handler.parentObject();
        if (o == null) {
            throw new ConfigurationError("No object to call method on");
        }
        if (handler.getLogger().isDebugEnabled()) {
            handler.getLogger().debug("Calling method {}({})",
                                      methodName,
                                      params.toString());
        }
        MethodUtils.invokeMethod(o,
                                 methodName,
                                 params.toArray());
    }
}
